using System.Collections.Generic;
using System.Linq;
using ReagentStore.ERM;

namespace ReagentStore.DAL
{
	public class ProductDAL : IDALBase<Product>
	{
		#region Implementation of IDALBase<T>

		public IList<Product> GetEntities()
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Products.ToList();
		}

		public Product GetEntityById(int id)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Products.SingleOrDefault(s => id.Equals(s.ProductID));
		}

		public void Insert(Product product)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				db.Products.AddObject(product);
				db.SaveChanges();
			}
		}

		public void Update(Product product)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Product exist = GetEntityById(product.ProductID);
				db.Products.Attach(exist);

				exist.Manufacturer = product.Manufacturer;
				exist.Specification = product.Specification;
				exist.Batch = product.Batch;
				exist.ExpirationDate = product.ExpirationDate;
				exist.ReagentID = product.ReagentID;

				db.SaveChanges();
			}
		}

		public void Delete(Product product)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
			{
				Product exist = GetEntityById(product.ProductID);
				db.Products.Attach(exist);
				db.Products.DeleteObject(exist);
				db.SaveChanges();
			}
		}

		#endregion

		public IList<Product> GetEntitiesByReagentId(int reagentId)
		{
			using (var db = new ReagentStoreContainer(new ConnectionStringBuilder().EntityConnectionString()))
				return db.Products.Where(w => reagentId.Equals(w.ReagentID)).ToList();
		}
	}
}